package com.example;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Random;

@Aspect
@Component
public class OrderServiceAspect {
    
    private Random random = new Random();
    
    // 定义切入点
    @Pointcut("execution(* com.example.OrderService.*(..))")
    public void orderServiceMethods() {}
    
    // 1. 前置增强
    @Before("orderServiceMethods()")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }
    
    // 2. 后置增强（只对add和delete方法）
    @AfterReturning(
        pointcut = "execution(* com.example.OrderService.add(..)) || execution(* com.example.OrderService.delete(..))",
        returning = "result"
    )
    public void afterReturningAdvice(Object result) {
        System.out.println("bye, 我是一个后置增强");
    }
    
    // 3. 获取方法返回值并输出
    @AfterReturning(
        pointcut = "orderServiceMethods()",
        returning = "result"
    )
    public void afterReturningResult(Object result) {
        if (result != null) {
            System.out.println("方法返回值: " + result);
        } else {
            System.out.println("方法无返回值");
        }
    }
    
    // 4. 计算方法执行时间
    @Around("orderServiceMethods()")
    public Object measureMethodExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        
        Object result = joinPoint.proceed();
        
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        
        System.out.println("方法执行时间: " + duration + " 毫秒");
        return result;
    }
    
    // 5. 权限检查（只对add和delete方法）
    @Around("execution(* com.example.OrderService.add(..)) || execution(* com.example.OrderService.delete(..))")
    public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        // 模拟权限检查（0有权限，1无权限）
        int permission = random.nextInt(2);
        
        if (permission == 0) {
            System.out.println("权限检查: 有权限，允许执行");
            return joinPoint.proceed();
        } else {
            System.out.println("权限检查: 无权限，终止方法执行");
            // 根据方法返回类型返回适当的值
            String methodName = joinPoint.getSignature().getName();
            if (methodName.equals("find")) {
                return 0; // 对于find方法返回0
            }
            return null; // 对于void方法返回null
        }
    }
}